<?php
namespace app\console\controller;

use think\Db;
use think\Url;
use think\Cache;
use think\Loader;
use think\Session;
use think\Request;
use think\Exception;
use think\Controller;
use app\client\model\ShopSpecAttr;
use app\console\model\Brand as BrandModel;
use app\client\model\ShopGoods as ShopGoodsModel;
use app\console\model\GoodsType as GoodsTypeModel;
use app\common\trilateral\Classify as ClassifyAlias;
use app\client\model\ShopGoodsSpec as ShopGoodsSpecModel;
use app\client\model\ShopGoodsAttr as ShopGoodsAttrModel;
use app\client\model\ShopGoodsType as ShopGoodsTypeModel;
use app\client\model\ShopGoodsFlag as ShopGoodsFlagModel;

class GoodsInventory extends Controller
{

    /*
     * 店铺商品列表
     */
    public function index()
    {
        // 获取参数
        $inquire = Request::instance()->param();

        // halt($inquire['orderId']);

        // 搜索条件
        $condition = [];

        if (!empty($inquire['title'])) $condition['title'] = ['like', '%' . $inquire['title'] . '%'];



        // 读取店铺商品
        $data = ShopGoodsModel::where($condition)->field('auding_time,auding_id,auding_status,id,price,parenTid,sort,sale_number,title,update_time,create_id,create_time,recommend,related,promotion,status,state,inventory_hint,charges,inventory,shop_recommend,goods_id')->paginate(10, false, ['query' => $inquire]);
        return $this->fetch('index', [
            'data'         => $data,
        ]);
    }

    public function update($id)
    {

        if (Request::instance()->isPost()) {

            $data = Request::instance()->param();
            if(!Request::instance()->param('sp_val/a')){
                fail('请添加商品规格');
            }
            // 验证
            $validate = Loader::validate('ShopGoods','validate',false,'client');
            if (!$validate->scene('create')->check($data)) fail($validate->getError());

            $model = new ShopGoodsModel();

            // 提交数据
            $dispose = $model->allowField(true)->save($data, ['id' => $id]);

            if (!empty($data['nameAttr'])) {
                // 一对多添加数组
                $flagArr = [];

                for ($i = 0; $i < count($data['nameAttr']); $i++) {

                    if (!empty($data['flag_id'][$i])) {
                        $flagArr[$i]['id'] = $data['flag_id'][$i];
                    }
                    $flagArr[$i]['goods_id'] = $id;
                    $flagArr[$i]['flag_name'] = $data['nameAttr'][$i];
                    $flagArr[$i]['flag_value'] = $data['valueAttr'][$i];
                }

                (new ShopGoodsFlagModel())->saveAll($flagArr);
            }

            if ($dispose !== false) {
                win('操作成功', Url::build('ShopGoods/index', ['orderId' => 'sort']));
            }

            fail('操作失败');

        }

        //获取分类id
        $goods_id = Request::instance()->param('goods_id');

        // 读取数据
        $item = ShopGoodsModel::get($id);

        $item['spec_attr'] = ShopSpecAttr::where(['goods_id' => $id])->select();

        if (empty($goods_id)) $goods_id = $item['goods_id'];

        // 读取店铺属性
        $attr = ShopGoodsSpecModel::where('goods_type_id' ,['like', '%,' . $goods_id . ',%'],['eq',''],'or')->fetchSql(false)->where('auding_status',2)->where('is_delete',1)->select();

        foreach ($attr as &$value) {
            // 获取attr参数
            $value['attribute'] = ShopGoodsAttrModel::where('spec_id','eq',$value['id'])->where('goods_type_id',['eq',$goods_id],['eq',0],'or')->select();
            //$value['attribute'] = ShopGoodsAttrModel::where('spec_id',['eq',$value['id']], 'goods_type_id',['eq',''])->select();
        }

        //halt($attr->toArray());
        // 读取店铺分类店铺商品
        $shopClassify = ShopGoodsTypeModel::where(['member_id' => Session::get('shop_id')])->field('id,title,parenTid,parentStr,count,sort')->select()->toArray();


        // 读取商品规格
        $flag_list = ShopGoodsFlagModel::all(['goods_id' => $id]);

//        $attr[1] = [
//            ['id' => 1,'goods_type_id' => ',2901,','member_id' => 0,'title' => '门店1','attribute' => [
//                'id' => '2240','goods_type_id' => 2901,'spec_id' => 1, 'title' => '原形'
//                ]
//            ]
//        ];
        //halt($attr->toArray());
        $shop = Db::name('shop')->where('auding_status',2)->where('is_delete',1)->select();
        $r = '';
        $d_shop = Db::name('shop_spec_attr')->field('DISTINCT shop_id')->where('goods_id',$id)->select()->toArray();
        $instr = [];
        if($d_shop){
            foreach ($d_shop as $k => $v){
                $instr[] = $v['shop_id'];
            }
            $r = implode(",",$instr);

        }
        $inventory_sum = Db::name('shop_spec_attr')->where('goods_id',$id)->sum('inventory');
        return $this->fetch('create', [
            "mate_title"   => '店铺商品编辑',
            'shopClassify' => ClassifyAlias::dimension($shopClassify),
            'attr'         => $attr,
            'd_shop' => $r,
            'item'         => $item,
            'shop' => $shop,
            'inventory_sum' => $inventory_sum,
            'flag_list'    => $flag_list

        ]);
    }







}
